<?php
class C_login extends Nvl_Controller{
	function __construct(){
		parent::__construct();
		session_start();
	}
	
	function verification(){
		$username = $this->input->post("login_username");
		$password = $this->input->post("login_password");
		if($username == 'nvl' && $password == 'noval'){
			$_SESSION[SESSION_USERID]='nvl';
			$_SESSION[SESSION_USERGROUPID]=0;
			$_SESSION[SESSION_PERSONNAME]='Noval Debby Prasetyono';
			$_SESSION[SESSION_SCHOOLID]=0;
			$_SESSION[SESSION_SCHOOLNAME]='';
			$_SESSION[SESSION_SCHOOLLVL]='';
		}else{
			$login_jenjang = $this->input->post('login_jenjang');
			$_SESSION[SESSION_SCHOOLLVL] = $login_jenjang;
			
			if($login_jenjang == 'dinas'){
				$sql = "
					SELECT 
						user_name AS user_name,
						user_password AS user_password, 
						user_usergroup_id AS user_usergroup_id,
						'0' AS sekolah_id,
						'' AS sekolah_nama,
						user_name AS user_nama
					FROM m_user 
					WHERE user_name = '". $username ."'";
				$query = $this->db->query($sql);
			}else{
				$DB = $this->switch_db();
				$sql = "
					SELECT 
						nik AS user_name, 
						password_rapor AS user_password,
						5 AS user_usergroup_id,
						siswa.npsn AS sekolah_id,
						sekolah.nama AS sekolah_nama,
						siswa.nama AS user_nama
					FROM siswa
					JOIN sekolah ON siswa.npsn = sekolah.npsn
					WHERE nik = '". $username ."'
				UNION
					SELECT
						user_rapor AS user_name,
						passwds AS user_password,
						CASE WHEN jabatan = '2' THEN 3 ELSE 4 END AS user_usergroup_id,
						pegawai.npsn AS sekolah_id,
						sekolah.nama AS sekolah_nama,
						pegawai.nama AS user_nama
					FROM pegawai 
					JOIN sekolah ON pegawai.npsn = sekolah.npsn
					WHERE user_rapor = '". $username ."'
				";
				$query = $DB->query($sql);
			}
			if($query->num_rows() > 0){
				$result = $query->row();
				if($result->user_name == $username && $result->user_password == md5($password)){
					$_SESSION[SESSION_USERID]=$username;
					$_SESSION[SESSION_USERGROUPID]=$result->user_usergroup_id;
					$_SESSION[SESSION_PERSONNAME]=$result->user_nama;
					$_SESSION[SESSION_SCHOOLID]=$result->sekolah_id;
					$_SESSION[SESSION_SCHOOLNAME]=$result->sekolah_nama;
				}else{
					$this->session->set_flashdata("msg","Login gagal.");
				}
			}else{
				$this->session->set_flashdata("msg","Login gagal.");
			}
		}
		redirect('c_main');
	}
	
	function logout(){
		$_SESSION[SESSION_USERID]='';
		session_destroy();
		redirect('c_main','refresh');
	}
}